from datetime import datetime
from typing import Optional
from uuid import UUID, uuid4

from bisheng.database.base import session_getter
from bisheng.database.models.base import SQLModelSerializable
from sqlalchemy import Column, DateTime, String, Text, text, desc, Integer
from sqlmodel import Field, SQLModel


class FaultWorkTicketBase(SQLModelSerializable):
    id: UUID = Field(nullable=False, primary_key=True, description='唯一ID')
    group_id: str = Field(sa_column=Column(String(length=255), default=''), description='告警记录ID')
    # line: str = Field(sa_column=Column(String(length=255), default=''), description='线路')
    # equipment_id: str = Field(sa_column=Column(String(length=255), default=''), description='设备ID')
    # equipment: str = Field(sa_column=Column(String(length=255), default=''), description='设备名称')
    # equipment_type: str = Field(sa_column=Column(String(length=255), default=''), description='设备类型')
    fault_type: str = Field(sa_column=Column(String(length=255), default=''), description='故障类型')
    work_address: str = Field(sa_column=Column(String(length=255), default=''), description='工作地址')
    work_content: str = Field(sa_column=Column(Text), default="", description='工作内容')
    work_start_time: Optional[datetime] = Field(sa_column=Column(DateTime), description='工作时间')
    work_end_time: Optional[datetime] = Field(sa_column=Column(DateTime))
    work_leader: str = Field(sa_column=Column(String(length=255), default=''), description='工作负责人')
    work_leader_phone: str = Field(sa_column=Column(String(length=255), default=''), description='工作负责人电话')
    work_member: str = Field(sa_column=Column(String(length=255), default=''), description='工作成员')
    work_person_num: int = Field(sa_column=Column(Integer, default=0), description='工作人数')
    work_command: str = Field(sa_column=Column(String(length=255), default=''), description='工作命令号')
    ticket_file_path: str = Field(sa_column=Column(String(length=255), default=''), description='工作票文件路径')
    code: str = Field(sa_column=Column(String(length=255), default=''), description='编号')
    chat_id: str = Field(sa_column=Column(String(length=255), default=''), description='chat_id')
    create_time: Optional[datetime] = Field(
        sa_column=Column(DateTime, nullable=False, server_default=text('CURRENT_TIMESTAMP')))


class FaultWorkTicket(FaultWorkTicketBase, table=True):
    id: UUID = Field(default_factory=uuid4, primary_key=True, unique=True)


class FaultWorkTicketDao:
    @staticmethod
    def create_fault_work_ticket(fault_work_ticket: FaultWorkTicket) -> FaultWorkTicket:
        """
        创建新的故障工单
        :param fault_work_ticket: FaultWorkTicket 对象
        :return: 创建并保存到数据库的 FaultWorkTicket 对象
        """
        with session_getter() as session:
            # 确保 fault_work_ticket 有一个 UUID
            if not fault_work_ticket.id:
                fault_work_ticket.id = uuid4()
            session.add(fault_work_ticket)
            session.commit()
            session.refresh(fault_work_ticket)
            return fault_work_ticket

    @staticmethod
    def get_fault_work_ticket_by_id(id):
        with session_getter() as session:
            if isinstance(id, str):
                id = UUID(id)
            query = session.query(FaultWorkTicket).filter(FaultWorkTicket.id == id)
            return query.first()

    @staticmethod
    def get_lastest_ticket():
        with session_getter() as session:
            query = session.query(FaultWorkTicket).order_by(desc(FaultWorkTicket.create_time))
            return query.first()

    @staticmethod
    def get_lastest_ticket_by_group_id(group_id):
        with session_getter() as session:
            query = session.query(FaultWorkTicket).filter(FaultWorkTicket.group_id == group_id).order_by(desc(FaultWorkTicket.create_time))
            return query.first()

    @staticmethod
    def get_fault_work_ticket_by_group_id_chat_id(group_id,chat_id):
        with session_getter() as session:
            query = session.query(FaultWorkTicket).filter(FaultWorkTicket.chat_id == chat_id,FaultWorkTicket.group_id==group_id).order_by(desc(FaultWorkTicket.create_time))
            return query.first()
